package com.beep.erp.model;

import android.animation.AnimatorSet;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.beep.erp.AppContext;
import com.beep.erp.MainActivity;
import com.beep.erp.R;
import com.beep.erp.model.login.LoginActivity;

import java.io.File;

/**
 * FileName: SplashActivity
 * description:启动页
 * Author: Jolly
 * Date: 2018/9/3
 */
public class SplashActivity extends Activity {
    private ImageView mSplashImage;
    private AnimatorSet mAnimatorSet;
    private static final int GO_MAIN = 100;
    private static final int GO_LOGIN = 200;
    // 动画执行时间
    private static final int ANIMATION_DURATION = 2000;
    // 缩放动画的结束值

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        mSplashImage = (ImageView) findViewById(R.id.iv_start);
    }


    /**
     * 执行欢迎页加载动画
     */
    private void animateImage(final int flag) {

        File dir = getFilesDir();
        final File imgFile = new File(dir, "start.jpg");
        if (imgFile.exists()) {
            mSplashImage.setImageResource(R.mipmap.start);
        } else {
            mSplashImage.setImageResource(R.mipmap.start);
        }
        new Handler().postDelayed(() -> {
            if (AppContext.getInstance().isLogin()) {
                MainActivity.start(SplashActivity.this);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                finish();
            } else {
                LoginActivity.start(this);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                finish();
            }
        }, ANIMATION_DURATION);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHandler.sendEmptyMessageDelayed(GO_MAIN, 0);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GO_MAIN:
                    animateImage(0);
                    break;
                case GO_LOGIN:
                    animateImage(1);
                    break;
            }
        }
    };

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }
}
